export default {
    namespaced: true,
    state: {
        cartData: []
    },
    mutations: {
        SET_CART(state, payload) {
            // state.cartData = payload

            //1.先检查cartData有没有传入的这条数据
            let target = state.cartData.find(item => item.id === payload.id)

            // - 没有
            if (!target) {
                //重新定义购物车的数据
                //将数据添加到cartData,第一次加入进来数量1,需要手动添加数量count这个字段
                let obj = {
                    title: payload.title,
                    price: payload.price,
                    count: 1,
                    id: payload.id
                }
                state.cartData.push(obj)
            } else {
                // - 有
                // 让数量count + 1
                // console.log(target)
                target.count++
            }

        }
    },
    actions: {
        ADD_CART(context, payload) {
            //这么写的目的是为了能够学到如何在一个模块的store操作另一个store的mutation或者action
            // console.log('cart action---', payload)
            context.commit('SET_CART', payload)
            //需要提交另一个store中的Mutation,
            //通过传入root:true,把这次操作转换为rootStore的操作等同于this.$store.commit('product/DECREASE_INVENTORY',payload.id)
            context.commit('product/DECREASE_INVENTORY', payload.id, { root: true })
        }
    },
    getters: {
        //总价计算
        total(state) {
            return (state.cartData.reduce((total, item) => {
                return total += item.price * item.count
            }, 0)).toFixed(2)
        }
    }
}